package cn.yunhe.java.security.service;

import cn.yunhe.java.dao.SysUserMapper;
import cn.yunhe.java.pojo.SysRoles;
import cn.yunhe.java.pojo.SysUser;
import cn.yunhe.java.security.user.MyPrincipal;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 从数据库查询账户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(StringUtils.isEmpty(username)){
            throw new BadCredentialsException("请输入账号！");
        }
        //1. 查询登录用户信息
        SysUser su = sysUserMapper.findByeLoginName(username);

        if(su==null){
            throw new BadCredentialsException("账号不存在！");
        }
        //用户权限=【角色+权限】
        Set<GrantedAuthority> authorities = new HashSet<>();

        //取角色和按钮(权限)信息
        List<Map<String,String>> rolesList = sysUserMapper.queryAllRights(su.getId());

        //lambda表达式
        rolesList.forEach((map) -> {
            map.forEach((k,v)->{
                //System.out.println(k+"----------------"+v);
                authorities.add(new SimpleGrantedAuthority(v));
            });
        });

        //自定义主体，可以携带更多信息
        MyPrincipal user = new MyPrincipal(su.getLoginName(),su.getPassword(),
                su.getUserStatus()==1,true,true,
                true,authorities);
        su.setPassword(null);
        user.setSysUser(su);

        //2. 将查询到的用户封装到框架使用的UserDetails对象中
        return user;
    }
}
